// 任务管理应用
document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const taskForm = document.getElementById('task-form');
    const taskInput = document.getElementById('task-input');
    const taskList = document.getElementById('task-list');
    const filterButtons = document.querySelectorAll('.filter-btn');
    const clearCompletedButton = document.getElementById('clear-completed');
    const totalCountElement = document.getElementById('total-count');
    const activeCountElement = document.getElementById('active-count');
    const completedCountElement = document.getElementById('completed-count');
    
    // 当前过滤状态
    let currentFilter = 'all';
    
    // 从本地存储加载任务
    let tasks = JSON.parse(localStorage.getItem('tasks')) || [];
    
    // 初始化应用
    function init() {
        renderTasks();
        updateTaskCount();
        
        // 添加事件监听器
        taskForm.addEventListener('submit', addTask);
        filterButtons.forEach(button => {
            button.addEventListener('click', filterTasks);
        });
        clearCompletedButton.addEventListener('click', clearCompletedTasks);
    }
    
    // 渲染任务列表
    function renderTasks() {
        // 清空当前任务列表
        taskList.innerHTML = '';
        
        // 根据过滤条件筛选任务
        let filteredTasks = tasks;
        if (currentFilter === 'active') {
            filteredTasks = tasks.filter(task => !task.completed);
        } else if (currentFilter === 'completed') {
            filteredTasks = tasks.filter(task => task.completed);
        }
        
        // 渲染筛选后的任务
        filteredTasks.forEach(task => {
            const taskItem = createTaskElement(task);
            taskList.appendChild(taskItem);
        });
    }
    
    // 创建任务元素
    function createTaskElement(task) {
        const li = document.createElement('li');
        li.className = `task-item ${task.completed ? 'completed' : ''}`;
        li.dataset.id = task.id;
        
        const checkbox = document.createElement('input');
        checkbox.type = 'checkbox';
        checkbox.className = 'task-checkbox';
        checkbox.checked = task.completed;
        checkbox.addEventListener('change', toggleTaskCompleted);
        
        const span = document.createElement('span');
        span.className = 'task-text';
        span.textContent = task.text;
        
        const deleteButton = document.createElement('button');
        deleteButton.className = 'task-delete';
        deleteButton.innerHTML = '&times;';
        deleteButton.addEventListener('click', deleteTask);
        
        li.appendChild(checkbox);
        li.appendChild(span);
        li.appendChild(deleteButton);
        
        return li;
    }
    
    // 添加新任务
    function addTask(e) {
        e.preventDefault();
        
        const taskText = taskInput.value.trim();
        if (taskText === '') return;
        
        const newTask = {
            id: Date.now(),
            text: taskText,
            completed: false,
            createdAt: new Date().toISOString()
        };
        
        tasks.push(newTask);
        saveTasks();
        renderTasks();
        updateTaskCount();
        
        // 清空输入框
        taskInput.value = '';
        taskInput.focus();
    }
    
    // 切换任务完成状态
    function toggleTaskCompleted(e) {
        const taskId = parseInt(e.target.parentElement.dataset.id);
        const task = tasks.find(task => task.id === taskId);
        
        if (task) {
            task.completed = e.target.checked;
            saveTasks();
            renderTasks();
            updateTaskCount();
        }
    }
    
    // 删除任务
    function deleteTask(e) {
        const taskId = parseInt(e.target.parentElement.dataset.id);
        tasks = tasks.filter(task => task.id !== taskId);
        saveTasks();
        renderTasks();
        updateTaskCount();
    }
    
    // 过滤任务
    function filterTasks(e) {
        currentFilter = e.target.dataset.filter;
        
        // 更新活动按钮状态
        filterButtons.forEach(button => {
            button.classList.remove('active');
        });
        e.target.classList.add('active');
        
        renderTasks();
    }
    
    // 清除已完成任务
    function clearCompletedTasks() {
        tasks = tasks.filter(task => !task.completed);
        saveTasks();
        renderTasks();
        updateTaskCount();
    }
    
    // 更新任务计数
    function updateTaskCount() {
        const totalCount = tasks.length;
        const activeCount = tasks.filter(task => !task.completed).length;
        const completedCount = totalCount - activeCount;
        
        totalCountElement.textContent = totalCount;
        activeCountElement.textContent = activeCount;
        completedCountElement.textContent = completedCount;
    }
    
    // 保存任务到本地存储
    function saveTasks() {
        localStorage.setItem('tasks', JSON.stringify(tasks));
    }
    
    // 初始化应用
    init();
});